package com.sykj.huxianlong.controller;




import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;



import com.sykj.bean.activiti.Process;

import com.sykj.huxianlong.pagemod.DataGrid;
import com.sykj.huxianlong.service.IFlowInfoService;
import com.sykj.util.reponse.ResultBody;

import org.activiti.editor.constants.ModelDataJsonConstants;

import org.activiti.engine.RepositoryService;

import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

/**
 *
 * 1  check-process-definitions: true #自动检查、部署流程定义文件
 * 2  创建一个新模板
 * 3  发起流程
 *
 *
 */


@RestController
@CrossOrigin
@RequestMapping("workflow")
public class HxlLeavenController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(HxlLeavenController.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    RepositoryService rep;

    private IFlowInfoService flowInfoService;



    @GetMapping("index")
    public List<Model> toIndex() {
        List<Model> list = repositoryService.createModelQuery().list();

        return list;
    }

    /**
     * 新建流程
     * @param request
     * @param response
     */
    @RequestMapping("/createModel")
    public void createModel(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, "name");
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, "description");
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName("name");
            modelData.setKey(StringUtils.defaultString("key"));

            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

            request.setAttribute("modelId", modelData.getId());

            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    //查询历史记录表
    @RequestMapping(value = "/getprocesslists", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<Process> getlist(@RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {
        int firstrow = (current - 1) * rowCount;
        List<ProcessDefinition> list = rep.createProcessDefinitionQuery().listPage(firstrow, rowCount);
        int total = rep.createProcessDefinitionQuery().list().size();
        List<Process> mylist = new ArrayList<Process>();
        for (int i = 0; i < list.size(); i++) {
            Process p = new Process();
            p.setDeploymentId(list.get(i).getDeploymentId());
            p.setId(list.get(i).getId());
            p.setKey(list.get(i).getKey());
            p.setName(list.get(i).getName());
            p.setResourceName(list.get(i).getResourceName());
            p.setDiagramresourcename(list.get(i).getDiagramResourceName());
            mylist.add(p);
        }
        DataGrid<Process> grid = new DataGrid<Process>();
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setRows(mylist);
        grid.setTotal(total);
        return grid;
    }




    /**
     * 撤销流程定义
     * @param modelId 模型ID
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/model/revokePublish")
    public ResultBody revokePublish(String modelId){
        ResultBody rb  = new  ResultBody();
        logger.info("撤销发布流程入参modelId：{}",modelId);
        Map<String, String> map = new HashMap<String, String>();
        Model modelData = repositoryService.getModel(modelId);
        if(null != modelData){
            try {
                /**
                 * 参数不加true:为普通删除，如果当前规则下有正在执行的流程，则抛异常
                 * 参数加true:为级联删除,会删除和当前规则相关的所有信息，包括历史
                 */
                repositoryService.deleteDeployment(modelData.getDeploymentId());

                rb.setCode("10001");
                rb.setMessage("撤销模型成功");
                repositoryService.deleteModel(modelId);
            } catch (Exception e) {

                rb.setCode("10002");
                rb.setMessage("撤销已部署流程服务异常");
            }
        }

        return rb;
    }


}
